package com.honour.controller.interfaced;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.honour.service.interfaced.ConvergeInManager;
import com.honour.service.interfaced.UserInManager;
import com.honour.service.interfaced.impl.AdvertisementInService;
import com.honour.service.interfaced.impl.EnergyInService;
import com.system.controller.base.BaseController;
import com.system.util.AppUtil;
import com.system.util.Const;
import com.system.util.DateUtil;
import com.system.util.FTPUtils;
import com.system.util.MapDistance;
import com.system.util.PageData;
import com.system.util.Tools;
import com.system.util.ToolsUtil;
import com.system.util.drools.DroolsFactory;


/**  汇聚主页接口
 @Function
 @Author 于泓磊
 @Date   2017年11月16日
*/
@Controller
@RequestMapping(value="/appconvergein")
public class ConvergeInController extends BaseController{
	
	@Resource(name="convergeinService")
	private ConvergeInManager coninService;
	
	@Resource(name="energyInService")
	private EnergyInService energyInService;
	
	@Resource(name="userinService")
	private UserInManager userinService;
	
	@Resource(name="advertisementInService")
	private AdvertisementInService advertisementInService;
	
	/**
	 * 获得汇聚列表接口
	 * @Author 于泓磊
	 * @date   2017年11月16日
	 * @return
	 */
	@RequestMapping(value="/convergelist")
	@ResponseBody
	public Object getConvergeList(){
		logBefore(logger, "获得汇聚列表接口");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("CONVERGELIST", pd.getString("FKEY"))){	//检验请求key值是否合法
				List<PageData> list = coninService.getConvergeList(pd);
					if (list.size()!=0) {
						 map.put("pd", list);
					}
					//返回01为查询成功并返回,02为查询为空
					result = (0 == list.size()) ?  "02" :  "01";
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	/**
	 * 获得指定汇聚下所有聚会列表(我发布,我参与)
	 * @Author 于泓磊
	 * @date   2017年11月16日
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/getpartylist")
	@ResponseBody
	public Object getPartyList(){
		logBefore(logger, "获得指定汇聚下所有聚会列表(我发布,我参与)");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("PARTYLIST", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("getPartyList", pd)){	//检查参数
					 List<PageData> list = new ArrayList<>();
					 if(pd.get("STATUS")!=null&&pd.get("STATUS").toString().length()!=0){
						 //判断STATUS状态0代表我发布 ， 1代表我参与
						 if(pd.get("STATUS").equals("0")){
							 list=coninService.getMyLaunchParty(pd);
						 }if(pd.get("STATUS").equals("1")){
							 list=coninService.getMyTakeParty(pd);
						 }
					 }else{
						 //用户ID为空查询所有聚会
						 list = coninService.getPartyList(pd);
						 List<PageData> ad = advertisementInService.getAdByConverge(pd);
						 map.put("ad", ad);
					 }
					 //返回01为查询成功并返回,02为查询为空
					 result = (0 == list.size()) ?  "02" :  "01";
					 for (PageData p : list) {
						 if (p.get("CONVERGEIMGS")!=null&&p.get("CONVERGEIMGS")!="") {
							 ToolsUtil.putImgstoArray(p, "CONVERGEIMGS");
						 }
						 p.put("MYHONOURUSER_ID", pd.get("HONOURUSER_ID"));
						//根据生日计算年龄
						String startTime = p.getString("BIRTHDAY");
						DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
						Date date =new Date();
						String endTime = fmt.format(date);
						p.put("age", DateUtil.getDiffYear(startTime, endTime));
					 }
					 for (PageData data : list) {
						Map<String, String> m= (Map<String, String>) getDistance(data);
						if(m.get("distance")==""){
							data.put("distance", 0);
						}else {
							data.put("distance", m.get("distance"));
						}
					 }
					 if (list.size()!=0) {
						 map.put("pd", list);
					 }
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 查看指定聚会详情
	 * @Author 于泓磊
	 * @date   2017年11月16日
	 * @return
	 */
	@RequestMapping(value="/getdetailbyid")
	@ResponseBody
	public Object getDetailById(){
		logBefore(logger, "查看指定聚会详情接口");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("DETAILID", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(pd!=null){
					pd=coninService.getDetailById(pd);
					ToolsUtil.putImgstoArray(pd, "CONVERGEIMGS");
					map.put("pd", pd);
					//返回01为查询成功并返回,02为查询为空
					result = (null == pd) ?  "02" :  "01";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 发起聚会(添加聚会)
	 * @Author 于泓磊
	 * @date   2017年11月16日
	 * @return
	 */
	@RequestMapping(value="/adddetailparty")
	@ResponseBody
	public Object addDetailParty(MultipartHttpServletRequest mreq,HttpServletResponse resp,HttpServletRequest request,String STARTTIME,String ENDTIME,Integer PRICEMIN,Integer PRICEMAX,String CONVERGEPER,Integer CONVERGESEX,Integer AGEMIN,Integer AGEMAX,String CONVERGETYPE,String CONVERGEDET,String CONVERGETITLE,String HONOURUSER_ID,String CONVERGE_ID,String CONVERGESORT_ID){
		logBefore(logger, "发起聚会(添加聚会)接口");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		String CONVERGEIMGS="";
		try{
			if(Tools.checkKey("DETAILADD", pd.getString("FKEY"))){	//检验请求key值是否合法
				//if(AppUtil.checkParam("addParty", pd)){	//检查参数
					List<MultipartFile> fileList = mreq.getFiles("fileList");
					// 创建一个通用的多部分解析器.  
			        // CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
			        // 设置编码  
			        // commonsMultipartResolver.setDefaultEncoding("utf-8");  
			        // 判断是否有文件上传  
			       // if (commonsMultipartResolver.isMultipart(request)){
			        	for (MultipartFile file : fileList) {
			        		//String filePath = "";
			        		if (file!=null&&file.getOriginalFilename().length()!=0&&file.getSize()!= 0) {
			        			//获得UUID之后的文件名
			        			String imgname=getUniqueFileName(file.getOriginalFilename());
			        			InputStream in = file.getInputStream();
			        			//获得文件全名
			        			try {
			        				resp.setCharacterEncoding("UTF-8");
			        				//resp.getWriter().write(filePath+";");
			        				//根据txt文件读取ftp工具类上传需要的参数
			        				String updeploy = Tools.readTxtFileAll(Const.UPDOWNLOADPATH, "UTF-8");
			        				String[] split = updeploy.split(",");
			        				//第一个参数为  图片服务器的地址
			        				//第二个参数为  图片服务器接口
			        				//第三/四个参数为  FTP服务器的登录用户名和密码
			        				//通过工具类获取图片服务器地址
			        				String imgpath = Tools.readTxtFileAll(Const.IMAGEPATH, "UTF-8");
			        				String path="convergeimgs/launchactivityimgs";
			        				FTPUtils.uploadFile(split[0], Integer.parseInt(split[1]), split[2], split[3], path, imgname, in);
			        				CONVERGEIMGS+=","+imgpath+path+"/"+imgname;
			        			} catch (Exception e) {
			        				e.printStackTrace();
			        			}
			        		}
			            }
						if(CONVERGEIMGS!=null&&CONVERGEIMGS.length()!=0){
							pd.put("CONVERGEIMGS", CONVERGEIMGS.substring(1));
						}else{
							pd.put("CONVERGEIMGS", "");
						}
				pd.put("CONVERGEDETAIL_ID", this.getSnowId());
				//发布时间
				Date date = new Date();
				String format = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
				pd.put("PUBLISHTIME", format);
				pd.put("STARTTIME", STARTTIME);
				pd.put("ENDTIME", ENDTIME);
				pd.put("PRICEMIN", PRICEMIN);
				pd.put("PRICEMAX", PRICEMAX);
				pd.put("CONVERGEPER", CONVERGEPER);
				pd.put("CONVERGESEX", CONVERGESEX);
				pd.put("AGEMIN", AGEMIN);
				pd.put("AGEMAX", AGEMAX);
				pd.put("CONVERGETYPE", CONVERGETYPE);
				pd.put("CONVERGEDET", CONVERGEDET);
				pd.put("CONVERGETITLE", CONVERGETITLE);
				pd.put("HONOURUSER_ID", HONOURUSER_ID);
				pd.put("CONVERGE_ID", CONVERGE_ID);
				pd.put("CONVERGESORT_ID", CONVERGESORT_ID);
				coninService.addDetailParty(pd);
				//使用Drools规则
				PageData energyScore = userinService.getEnergyScore(pd);
				Integer energy = energyInService.getPublishPartyScore(pd);
				energyScore.put("energy", energy);
				DroolsFactory.excuteDrools(energyScore);
				userinService.updEnergyScore(energyScore);
				//返回01为查询成功并返回
				result =   "01";
//				}else {
//					result = "03";
//				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 用户参加别人发起的聚会(添加聚会)
	 * @Author zhaozhenhua
	 * @date   2017年12月04日
	 * @return
	 */
	@RequestMapping(value="/addotherparty")
	@ResponseBody
	public Object addOtherParty(){
		logBefore(logger, "用户参加别人发起的聚会(添加聚会)");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("OTHRERPARTYADD", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("addOtherParty", pd)){	//检查参数
				pd.put("TAKEPARTY_ID", this.getSnowId());
				coninService.addOtherParty(pd);
				//使用Drools规则
				PageData energyScore = userinService.getEnergyScore(pd);
				Integer energy = energyInService.getTakePartyScore(pd);
				energyScore.put("energy", energy);
				DroolsFactory.excuteDrools(energyScore);
				userinService.updEnergyScore(energyScore);
				//返回01为查询成功并返回
				result =   "01";
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 *	根据经纬度计算距离
	 * @param args
	 * @throws Exception
	 */
	public Object getDistance(PageData pd){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success",distance="";
		try {
			PageData p = coninService.getDistanceUserAndUser(pd);
			distance  = MapDistance.getDistance(p.getString("MYUSERLONGITUDE"),p.getString("MYUSERLATITUDE"),p.getString("USERLONGITUDE"),p.getString("USERLATITUDE"));
		} catch (Exception e) {
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		map.put("distance", distance);			//距离
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 多文件上传辅助方法
	 * @param originalFileName
	 * @return
	 * @Author 于泓磊
	 */
	private String getUniqueFileName(String originalFileName) {
		String ext=null;
		if(originalFileName.indexOf(".")!=-1){
			ext = originalFileName.substring(originalFileName.lastIndexOf("."),originalFileName.length());
		}else{
			ext="."+originalFileName;
		}
		UUID uuid = UUID.randomUUID();
		String uniqueFileName = uuid+ext;
		String replace=uniqueFileName.replace("-", "");
		return replace;

	}
	
	/**
	 * 根据汇聚ID查询分类列表
	 * @Author zhaozhenhua
	 * @date   2017年12月26日
	 * @return
	 */
	@RequestMapping(value="/getconvergesort")
	@ResponseBody
	public Object getConvergeSortById(){
		logBefore(logger, "根据汇聚ID查询分类列表");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("GETCONVERGESORT", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("getConvergeSortById", pd)){	//检查参数
					List<PageData> list = coninService.getConvergeSortById(pd);
					map.put("pd", list);
				//返回01为查询成功并返回
				result =   "01";
				}else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
}
